﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;

using OgilvyOne.Model;
using OgilvyOne.IDAL;
using OgilvyOne.DALFactory;
using OgilvyOne.Utility;

namespace OgilvyOne.BLL
{
    public class CmsUserSessionBll
    {
        public void Add (string name, UsersModel model)
        {
            string clientIP = HttpRequestUtil.GetClientIP();
            //string clientMac = HttpRequestUtil.GetClientMac();

            //此处先判断当前IP和MAC在Session表中是否存在，如果存在，则先删除
            if (CmsUserSessionFactory.create().GetUserSessionModel(clientIP) != null)
                CmsUserSessionFactory.create().Delete(clientIP);

            CmsUserSessionModel sessionModel = new CmsUserSessionModel();
            sessionModel.ClientIP = clientIP;
            //sessionModel.ClientMac = clientMac;
            sessionModel.UserID = model.Aid;

            CmsUserSessionFactory.create().Insert(sessionModel);
        }

        public UsersModel GetUserFromSession()
        {
            string clientIP = HttpRequestUtil.GetClientIP();
            //string clientMac = HttpRequestUtil.GetClientMac();

            CmsUserSessionModel sessionModel = CmsUserSessionFactory.create().GetUserSessionModel(clientIP);
            if (sessionModel == null) return null;

            //如果sessionModel不为null，需要判断LoginTime距离当前时间是否已经超出超时限制，如果是，返回null
            TimeSpan span = DateTime.Now.Subtract(sessionModel.LoginTime);
            if (span.Seconds > ConfigUtil.GetIntValue("SessionTimeout"))   //超时
                return null;

            //将LoginTime更新为当前时间
            CmsUserSessionFactory.create().UpdateLoginTime(clientIP);

            UsersBll bll = new UsersBll();
            UsersModel user = bll.GetModel(sessionModel.UserID);
            return user;
        }

        public bool Remove() 
        {
            try
            {
                string clientIP = HttpRequestUtil.GetClientIP();
                //string clientMac = HttpRequestUtil.GetClientMac();
                return CmsUserSessionFactory.create().Delete(clientIP);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error occurred in CmsUserSessionBll.Remove. Message: {0}", ex.Message));
            }
        }
    }
}
